/*
 * Copyright (C) 2013 Andreas Stuetz <andreas.stuetz@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.redkite.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import com.redkite.app.InfinityScrollListActivity.YourRunnable;
import com.redkite.app.layout.ListItemRelativeLayout;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;

public class CardFragment extends Fragment {

	private static final String ARG_POSITION = "position";

	private int position;

	public static CardFragment newInstance(int position) {
		CardFragment f = new CardFragment();
		Bundle b = new Bundle();
		b.putInt(ARG_POSITION, position);
		f.setArguments(b);
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		position = getArguments().getInt(ARG_POSITION);
		
        
        
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		RelativeLayout relativeLayout = new RelativeLayout(this.getActivity());
		relativeLayout.setLayoutParams(params);
		list = new ListView(this.getActivity());
		relativeLayout.addView(list);
        List<String> mList = new ArrayList<String>();
        String str;
        for(int i=0;i<10;i++){
            str = new String("Data --- "+i);
            mList.add(str);
        }
        LAdapter adapter = new LAdapter(this.getActivity(),0,mList);
        list.setAdapter(adapter);
        final YourRunnable runy = new YourRunnable();


        list.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN ){

                    startTime= (new Date()).getTime();
                    runy.onPause();//pausing thread actually pauses scrolling
                }
                if(event.getAction() == MotionEvent.ACTION_UP){
                    endTime= (new Date()).getTime();
                    if((endTime - startTime)<=100){//100 mill second limit for click


                        //Log.i("ITEM CLICK() ", "item : ");
                    }

                    runy.onResume(); //resume scrolling         
                }

                return false;
            }


        });
        new Thread(runy).start();
		return relativeLayout;
	}
	ListView  list;
    long startTime;
    long endTime;
  

    class YourRunnable implements Runnable {
        private Object mPauseLock;
        private boolean mPaused;
        private boolean mFinished;

        public YourRunnable() {
            mPauseLock = new Object();
            mPaused = false;
            mFinished = false;
        }

        public void run() {
            while (!mFinished) {
                //for loop is not infinite but enough as Integer.MAX_VALUE
                 for (int index = 0; index < list.getAdapter().getCount(); index++) {
                        list.smoothScrollToPositionFromTop(list.getLastVisiblePosition() + 1, 0, 10000);
                        try {
                            // it helps scrolling to stay smooth as possible (by experiment)
                            Thread.sleep(10000);
                            synchronized (mPauseLock) {
                                while (mPaused) {
                                    try {
                                        mPauseLock.wait();//putting thread in wait list of mPauseLock object
                                    } catch (InterruptedException e) {
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }


            }
        }

        /**
         * Call this method to pause thread.
         */
        public void onPause() {
            synchronized (mPauseLock) {
                mPaused = true;
            }
        }

        /**
         * Call this method to resume thread.
         */
        public void onResume() {
            synchronized (mPauseLock) {
                mPaused = false;
                mPauseLock.notifyAll();//notify all object that are waiting on the wait list of mPauseLock object
            }
        }

    }
    private class LAdapter extends ArrayAdapter{

        List<String> mlist;
        Context mContext;
        LayoutInflater inflater;
        public final int HALF_MAX_VALUE = Integer.MAX_VALUE/2;
        public final int MIDDLE;

        public LAdapter(Context ctx,int resId, List<String> objects){
            super(ctx, resId, objects);
            mContext = ctx;
            mlist = objects;
            inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            MIDDLE = HALF_MAX_VALUE - HALF_MAX_VALUE % mlist.size();

        }


        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return 20;
        }

        @Override
        public String getItem(int position) {
            // TODO Auto-generated method stub
            int relativePos = position %  mlist.size();
            Log.i("RELATIVE : "," POS:"+relativePos);
            return mlist.get(relativePos);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            RelativeLayout layoutProduct1 = null;
            RelativeLayout layoutProduct2 = null;

            if (convertView == null) 
            {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.p_sample_item, parent, false);
                holder.name = (ListItemRelativeLayout) convertView.findViewById(R.id.p_list_items);
                layoutProduct1 = (RelativeLayout) inflater.inflate(R.id.p_layout_product1, parent, false);
                layoutProduct2 = (RelativeLayout) inflater.inflate(R.id.p_layout_product1, parent, false);
                
                convertView.setTag(holder);
            } 
            else 
            {
                holder = (ViewHolder) convertView.getTag();
            }

            String model = getItem(position);


            convertView.setOnClickListener(new ListenerT(model) {

                @Override
                public void onClick(View v) {
                    Log.i("CLICK", "ITEM---"+name );

                }
            });

            return convertView;

        }


    }

    //use your own listener to pass parameter
    private class ListenerT implements OnClickListener{

        String name;
        public ListenerT(String nm){
            name = nm;
        }
        @Override
        public void onClick(View v) {


        }

    }
    private class ViewHolder{
    	ListItemRelativeLayout name;
    }


}